import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const token = uni.getStorageSync('token') || '';
// console.log(token)
const userInfo = uni.getStorageSync('userInfo') || {};

const store = new Vuex.Store({
    state: {
        //用户token
        token,
        //用户信息
        userInfo,
        //网络状态，用于下载提醒
        networkState: 'unknown'
    },
    getters: {
		// 获取网络状态
		networkStatus: state => {
			return state.networkState;
		},
        // 判断用户是否登录
        hasLogin: state => {
            if (state.token) {
                return true;
            } else {
                return false
            }
        }
    },
    mutations: {
        login(state, provider) {
			state.token = provider.token;
			console.log(state.token)
			uni.setStorageSync('token', provider.token);
        },
        logout(state) {
            state.token = '';
            state.userInfo = {};
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
        },
		setUserInfo(state , e) {
			console.log(e)
			state.userInfo = e;
			uni.setStorageSync('userInfo', e);
		},
        setNetworkState(state, provider) {
            state.networkState = provider;
        }
    },
    actions: {
        networkStateChange({commit}, info) {
            commit('setNetworkState', info);
        },
        reLogin({commit}, info) {
            commit('logout', '');
            $mRouter.redirectTo({
                route: $mRoutesConfig.login
            });
        },
        logout({commit}, info) {
            commit('logout');
        }
    }
})

export default store
